from flask import Flask,render_template,request,session,url_for,redirect,send_from_directory
from db import *
from get_api import *
from pymysql import connect



app = Flask(__name__)
app.secret_key = 'please-generate-a-random-secret_key'
#主页
@app.route('/')   
def login():
    return  render_template("login.html")

#注册
@app.route('/regist.html')
def regist():
    return render_template('regist.html')


#注册结果
@app.route('/result.html',methods=['GET','POST'])  
def regist_reuslt():
    if request.method =='POST':        #当前端发post请求到result.html地址时执行以下操作 判断注册是否成功
        if regist_user(request.form['tel'], request.form['userName'], request.form['password']):        
            return render_template('regist_result.html')
        else:
            return render_template("regist_fail.html")


#忘记密码
@app.route('/forget.html')
def forget():
    return render_template('forget.html')


#找回密码
@app.route('/search.html',methods=['GET','POST'])
def search():
    if request.method == 'POST':         #当前端发post请求到search.html地址时执行以下操作，去数据库查找密码信息
        if seach_pass(request.form['tel'], request.form['userName']):
            return render_template('password.html',password = seach_pass(request.form['tel'], request.form['userName']))
        else:
            return render_template('no_password.html')
#验证登录
@app.route('/success.html',methods=['GET','POST'])
def check_in():
    while True:
        if request.method == 'POST':         #判断是否post请求
            res = check_login(request.form['tel'], request.form['password']) #拿输入的用户名和密码取数据查找是否有一致的
            if res:
                session['username'] = request.form['tel']         #成功后保存用户名
                session['password'] = request.form['password']
                session['name'] = res
                return render_template('pic.html',name=res)
            
            else:
                return render_template('no_password.html')

#bicycle 骑行页面
@app.route('/bicycle')
def bicycle():
    try:
        if session['username']:     #判断是否非法的用户直接访问
            return render_template('bicycle.html')

    except Exception as a:
        return redirect(url_for('login'))

#walk  行走页面
@app.route('/walk')
def walk():
    try:
        if session['username']:   #判断是否非法的用户直接访问
            return render_template('walk.html')

    except Exception as a:
        return redirect(url_for('login'))

#driver  驾车页面
@app.route('/driver')
def driver():
    try:
        if session['username']:
            return render_template('driver.html')

    except Exception as a:
        return redirect(url_for('login'))


#cloud  天气页面
@app.route('/cloud')
def cloud():
    try:
        if session['username']:
            return render_template('cloud.html')

    except Exception as a:
        return redirect(url_for('login'))

#log  日志页面
@app.route('/log')
def log():
    try:
        if session['username']:
            res = search_record(session['username'])  #根据用户信息去数据库 查找该用户的记录
            return render_template('log.html',res =res)

    except Exception as a:
        return redirect(url_for('login'))


#通过高德api获取骑行路线
@app.route('/getbicycle',methods=['POST','GET'])
def getbicycle():
    if request.method == 'POST':  #判断是否为post
        try:
            if session['username']:         #判断用户是否为非法
                res="起点和终点输入有误，查询无结果 "         #初始化变量
                if request.form['origin'] and request.form['destination']: #判断是否有输入起点和终点
                    origin = get_geo(request.form['origin']) #调用高德api获取地点经纬度
                    destination =get_geo(request.form['destination'])##调用高德api获取终点经纬度
                    if origin != 'null' and destination != 'null': #判断经纬度是否获取成功
                        res = bicycling(origin,destination)      ##调用高德api根据经纬度获取路线
                        search_location = "起点：{}-终点：{}".format(request.form['origin'],request.form['destination'])   #拼接搜索内容
                        insert_record(session['username'],str('骑车路径'),str(search_location))  #把操作记录存到数据库 方便录入日志
                        return render_template('bicycle.html', res=res)
                return render_template('bicycle.html',res =res)

        except Exception as a:
            return redirect(url_for('login'))

#过高德api获取行走路线
@app.route('/getwalk',methods=['POST','GET'])
def getwalk():
    if request.method == 'POST':
        try:
            if session['username']:#判断用户是否为非法
                res="起点和终点输入有误，查询无结果 "
                if request.form['origin'] and request.form['destination']: #判断是否有输入起点和终点
                    origin = get_geo(request.form['origin']) #获取地点经纬度
                    destination =get_geo(request.form['destination'])#获取终点经纬度
                    if origin != 'null' and destination != 'null': #判断经纬度是否获取成功
                        res = cheack_walk(origin,destination)   #获取路线
                        search_location = "起点：{}-终点：{}".format(request.form['origin'], request.form['destination']) #拼接搜索内容
                        insert_record(session['username'], str('步行路径'), str(search_location)) #把操作记录存到数据库 方便录入日志
                        return render_template('walk.html', res=res)
                return render_template('walk.html',res =res)

        except Exception as a:
            print(a)
            return redirect(url_for('login'))
#过高德api获取驾车路线
@app.route('/getdriver',methods=['POST','GET'])
def getdriver():
    if request.method == 'POST':   
        try:
            if session['username']:   #判断用户是否为非法
                res="起点和终点输入有误，查询无结果 "
                if request.form['origin'] and request.form['destination']: #判断是否有输入起点和终点
                    origin = get_geo(request.form['origin']) #获取地点经纬度
                    destination =get_geo(request.form['destination'])#获取终点经纬度
                    if origin != 'null' and destination != 'null': #判断经纬度是否获取成功
                        res = driving(origin,destination)          #获取路线
                        search_location = "起点：{}-终点：{}".format(request.form['origin'], request.form['destination']) #拼接搜索记录
                        insert_record(session['username'], str('驾车路径'), str(search_location))  #把操作记录存到数据库 方便录入日志
                        return render_template('driver.html', res=res)
                return render_template('driver.html',res =res)

        except Exception as a:
            print(a)
            return redirect(url_for('login'))
#过高德api获取天气
@app.route('/getcloud',methods=['POST','GET'])
def getcloud():
    if request.method == 'POST':
        try:
            if session['username']:   #判断用户是否为非法
                res="起点和终点输入有误，查询无结果 "
                if  request.form['city'] : #判断是否有输入城市
                    city = request.form['city']
                    res = weather(city)  #查询城市天气
                    if city != 'null': #判断经纬度是否获取成功
                        insert_record(session['username'], str('天气'), str(city))  #入数据库 方便记录日志
                        return render_template('cloud.html', res=res)
                return render_template('cloud.html',res =res)

        except Exception as a:
            return redirect(url_for('login'))

if __name__ == '__main__':

    app.run(debug=True,port=80)               #debug模式，可以调试程序一般没用需要在pycharm中勾选